﻿using System;
using System.Windows;
using Microsoft.Phone.Scheduler;
using System.Diagnostics;

namespace CCWP7.CaliburnMicro.Services
{
    public class AgentController
    {
        private const string STR_BackgroundTask = "BackgroundTask";
        public void RegisterAgent()
        {
            var actionService = ScheduledActionService.Find(STR_BackgroundTask);

            if (actionService != null)
            {
                Debug.WriteLine("IsScheduled: {0} IsEnabled: {1}", actionService.IsScheduled, actionService.IsEnabled);

                if (!actionService.IsScheduled || actionService.ExpirationTime < DateTime.Now.AddDays(7))
                {
                    Debug.WriteLine("Task expiration: {0}", actionService.ExpirationTime);

                    ScheduledActionService.Remove(STR_BackgroundTask);

                    actionService = null;
                }
            }

            if (actionService == null)
            {
                var scheduledTask = new PeriodicTask(STR_BackgroundTask) { Description = "Live Tile service for CCNet Monitor",
                ExpirationTime = DateTime.Now + TimeSpan.FromDays(14) };

                try
                {
                    ScheduledActionService.Add(scheduledTask);
                    actionService = ScheduledActionService.Find(scheduledTask.Name);
                }
                catch (InvalidOperationException ex)
                {
                    MessageBox.Show("Can't schedule agent; either there are too many other agents scheduled or you have disabled this agent in Settings: " + ex.Message);
                }
            }
#if DEBUG
            if (actionService != null)
                try
                {
                    ScheduledActionService.LaunchForTest(STR_BackgroundTask, TimeSpan.FromSeconds(3));
                }
                catch (InvalidOperationException ex)
                {
                    Debug.WriteLine("Failed to launch for test: " + ex.Message);
                }
#endif
        }
    }
}
